package org.easy.byteasr;

import org.easy.byteasr.dto.AudioFormat;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class ByteRealtimeAsrV3Template {

    private final ConcurrentHashMap<String, ByteAsrWebsocketHolder> registry = new ConcurrentHashMap<>();

    private final ByteRealtimeAsrV3Client byteRealtimeAsrV3Client;

    public ByteRealtimeAsrV3Template(org.easy.byteasr.ByteRealtimeAsrV3Client byteRealtimeAsrV3Client) {
        this.byteRealtimeAsrV3Client = byteRealtimeAsrV3Client;
    }

    public String initGetSessionId(String userId, AudioFormat audioFormat, ByteAsrWebSocketListener listener) {
        if (registry.containsKey(userId)) {
            return userId;
        }

        final CountDownLatch latch = new CountDownLatch(1);
        ByteAsrWebsocketHolder init = byteRealtimeAsrV3Client.init(listener, latch, audioFormat);
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        registry.put(userId, init);
        return userId;
    }


    public void sendAudioOnlyWithSeq(String userId, byte[] buffer, boolean isFirst) {
        ByteAsrWebsocketHolder holder = registry.get(userId);
        if (isFirst) {
            finishSession(userId);

            initGetSessionId(userId, holder.getAudioFormat(), holder.getListener());

            holder = registry.get(userId);

            byteRealtimeAsrV3Client.sendAudioFirst(holder.getWebSocket(), userId, holder.getAudioFormat());
            holder.setSeq(1);
        }
        holder.setSeq(holder.getSeq() + 1);
        byteRealtimeAsrV3Client.sendAudioOnlyWithSeq(holder.getWebSocket(), buffer, buffer.length, false, holder.getSeq());

    }


    public void finishSession(String userId) {
        ByteAsrWebsocketHolder holder = registry.remove(userId);
        if (holder != null && holder.getWebSocket() != null) {
            holder.getWebSocket().close(1000, "close");
        }

    }
}
